"""Adjust kcidb dumpfiles."""
import argparse
import glob
import os

from cki_lib import misc
from cki_lib.kcidb.file import KCIDBFile
from cki_lib.misc import get_nested_key
import sentry_sdk


def merge_upt_dumpfiles(path2file):
    """Merge partial kcidb_all files into main kcidb_all."""
    main_file = KCIDBFile(path2file)

    for fname in glob.glob(f'{os.environ["UPT_RESULTS"]}*/results_*/kcidb_*.json'):
        partial_file = KCIDBFile(fname)
        for test in partial_file.data.get('tests', []):
            test_main_file = main_file.get_test(test['id'])
            key = 'misc/rerun_index'

            # Ensure we only save the newest test result if reruns were needed.
            if get_nested_key(test, key, 1) >= get_nested_key(test_main_file, key, 1):
                main_file.set_test(test['id'], test)

    main_file.save()


def main(args: list[str] | None = None) -> None:
    """Do all."""
    parser = argparse.ArgumentParser()
    parser.parse_args(args)

    merge_upt_dumpfiles(os.environ['KCIDB_DUMPFILE_NAME'])


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk)
    main()
